from gis.common import track_logging
import re
from decimal import Decimal

from gis.common.exceptions import BizException
from gis.common.timer import api as timer_api
from itpay.core.agency.const import BankCode
from itpay.core.recharge_order import order_service
from itpay.core.recharge_order.const import *
from itpay.core.recharge_order.errors import *
from itpay.core.recharge_order.models import BankCardSms

_LOGGER = track_logging.getLogger(__name__)

# 银行官方短信发送号码
BANK_PHONE_MAP = {
    '95533': BankCode.CCB,
    '95599': BankCode.ABC,
    '95588': BankCode.ICBC,
    '95566': BankCode.BOC,
    '95559': BankCode.BCM,
    '95508': BankCode.CGB
}


def save_sms(out_id, phone, from_phone, content, sms_time):
    sms = BankCardSms(out_id=out_id, phone=phone, from_phone=from_phone, content=content, sms_time=sms_time)
    sms.save()

    # 处理
    timer_api.add_task(TASK_SMS_MATCH_ORDER, sms.id)

    return sms.to_dict()


def _get_sms(sms_id):
    m_sms = BankCardSms.objects.filter(pk=sms_id).first()
    if not m_sms:
        raise BizException(ERROR_SMS_NOT_EXISTS)
    return m_sms


def exists_sms(out_id):
    return BankCardSms.objects.filter(out_id=out_id).exists()


def match_sms_and_commit_order(sms_id):
    """
    解析短信内容，并根据金额匹配订单后自动发起上分操作
    """
    m_sms = _get_sms(sms_id)
    bank_code = BANK_PHONE_MAP.get(m_sms.from_phone)
    if not bank_code:
        raise BizException(ERROR_SMS_FROM_PHONE_NOT_BANK)
    amount = _parse_amount_from_content(m_sms.content)
    if not amount:
        raise BizException(ERROR_SMS_CONTENT_NOT_TRANS)

    m_sms.bank_code = bank_code.value
    m_sms.amount = amount
    m_sms.save()

    order = order_service.get_order_by_bankcard_phone_and_real_amount(m_sms.phone, amount)
    order_service.commit_order(order['id'], channel_order_no=str(sms_id), remark='commit by match sms')

    m_sms.recharge_order_id = order['id']
    m_sms.save()


_AMOUNT_IN_PATTERN = re.compile(r'收入人民币([\d.]+)元')
_AMOUNT_OUT_PATTERN = re.compile(r'支出人民币([\d.]+)元')


def _parse_amount_from_content(content):
    # 短信格式：
    # 您尾号xxxx的储蓄卡账户1月31日13时20分支付机构提现收入人民币199.96元,活期余额2233.39元。[建设银行]
    # 您尾号xxxx的储蓄卡账户2月2日14时26分收费支出人民币7.50元,活期余额31092.41元。[建设银行]
    in_match = _AMOUNT_IN_PATTERN.search(content)
    amount_str = None
    if in_match:
        amount_str = in_match.group(1)
    else:
        out_match = _AMOUNT_OUT_PATTERN.search(content)
        if out_match:
            amount_str = '-' + out_match.group(1)
    if amount_str:
        return int(Decimal(amount_str) * 100)


class MatchRechargeOrderHandler(timer_api.TaskHandler):
    def handle(self, task):
        sms_id = int(task.biz_num)
        try:
            match_sms_and_commit_order(sms_id)
        except BizException as e:
            _LOGGER.info('process sms auto trans fail, the sms_id : {}, cause : {}'.format(sms_id, e))

    def get_biz_code(self):
        return TASK_SMS_MATCH_ORDER
